package com.sinbad.interview.solution.question02.case02;

import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.Objects;

/**
 * @author sinbad.cheng
 * @since 2025-04-14 17:52
 */
public class MaxDuplicateFinder {

    /**
     * 测试入口主函数
     */
    public static void main(String[] args) throws IOException {
        String inputFile = "numbers.txt";
        String bucketDir = "buckets";
        int bucketCount = getOptimalBucketCount(new File(inputFile));

        // Step 1: 分桶
        BucketSplitter.splitFile(inputFile, bucketDir, bucketCount);

        // Step 2: 每个桶统计
        File dir = new File(bucketDir);
        Map.Entry<Integer, Integer> maxEntry = null;
        for (File bucket : Objects.requireNonNull(dir.listFiles())) {
            Map.Entry<Integer, Integer> entry = BucketProcessor.getMostFrequentFromBucket(bucket);
            if (maxEntry == null || (entry != null && entry.getValue() > maxEntry.getValue())) {
                maxEntry = entry;
            }
        }

        if (maxEntry != null) {
            System.out.println("重复最多的数字是：" + maxEntry.getKey() + "，出现次数：" + maxEntry.getValue());
        } else {
            System.out.println("文件为空或无有效数据");
        }
        
        BucketProcessor.cleanUp();
    }

    private static int getOptimalBucketCount(File file) {
        long fileSizeMB = file.length() / (1024 * 1024);
        return (int) Math.max(100, Math.min(10000, fileSizeMB * 5)); // 可调策略
    }
}
